package com.doaio.api;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @deprecation 七牛云服务
 * @package com.doaio.api
 * @author 雷楚桥
 * @email leichuqiao@126.com
 * @date 2018/11/22 16:44
 */
public class QiniuCloudService {

    private static final String ACCESS_KEY = "vDkF8--pwwnpTKxS1PB2usTvkfu7DfDtPU0v7EeV";
    private static final String SECRET_KEY = "plfZsPAvERe2AmyT9q7_YOvncmgDlpZ-igyoqqUh";

    // 仓库
    private static final String BUCKET = "doaio";

    // 七牛云外网访问地址
    public static final String QINIU_UPLOAD_SITE = "http://img.doaio.com/";

    public static String upload(MultipartFile file, String fileName) {

        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone2());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);
        try {
            Response response = null;

            response = uploadManager.put(file.getInputStream(), fileName, upToken, null, null);

            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
//            System.out.println(putRet.key);
//            System.out.println(putRet.hash);
            return putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
